package common;

import java.util.concurrent.atomic.AtomicLong;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.Attribute;
import rpc.sync.Request;

/**
 * 网络通讯channel
 * @author King
 *
 */
public class NetChannel
{
	private Channel channel;
	
	/**自增的id**/
	private static final AtomicLong autoChannelId = new AtomicLong(0); 
	
	private long channelId;
	
	/**可能为user**/
	private Object cahceInfo;
	
	/**是否被踢了**/
	private volatile boolean isKick;
	/**是否触发心跳  true在下次心跳未收到消息将断开连接**/
	private boolean heartBeat;
	
	
	public NetChannel(Channel channel)
	{
		System.out.println("有一个连接进入"+channel.remoteAddress());
		Attribute<NetChannel> netChannel = channel.attr(ServerAttributeKey.netChannel);
		netChannel.set(this);
		Attribute<Long> attribute = channel.attr(ServerAttributeKey.channel_Id);
		this.channelId = autoChannelId.addAndGet(1);
		attribute.set(this.channelId);
		this.channel = channel;
	}
	
	public void write(Object obj)
	{
		channel.writeAndFlush(obj);
	}
	
	public void writeAndClose(Object obj)
	{
		channel.writeAndFlush(obj).addListener(new ChannelFutureListener() {

			public void operationComplete(ChannelFuture future) throws Exception {
				future.channel().close();
			}
        });
	}
	
	
	@SuppressWarnings("unchecked")
	public <T> T call(Object obj,Class<T> cls)
	{
//		Response response = new Response();
		//
		
		
//		response.waitFor();
//		return (T)response.getBody();
		return null;
	}
	
	

	public long getChannelId() {
		return channelId;
	}

	@SuppressWarnings("unchecked")
	public <T extends Object> T getCahceInfo() {
		if(cahceInfo==null)
			return null;
		return (T)cahceInfo;
	}

	public void setCahceInfo(Object cahceInfo) {
		this.cahceInfo = cahceInfo;
	}

	public void setChannelId(long channelId) {
		this.channelId = channelId;
	}

	public Channel getChannel() {
		return channel;
	}

	public boolean isKick() {
		return isKick;
	}

	public void setKick(boolean isKick) {
		this.isKick = isKick;
	}

	public boolean isHeartBeat() {
		return heartBeat;
	}

	public void setHeartBeat(boolean heartBeat) {
		this.heartBeat = heartBeat;
	}
	
}

